﻿

$.validator.addMethod("pattern", function (value, element, param) {
    return this.optional(element) || param.test(value);
}, "Invalid format.");

$.validator.addMethod("inarray", function(value, element, param) {
    return this.optional(element) || $.inArray(value, param) >= 0; // <-- Check if the value is in the array.
}, "Not in Array");

$.validator.addMethod("asciilength", function (value, element, param) {
    var range = [];
    if (!isArray(param)) {
        range = [null, param];
    } else {
        
        range = param;
    }

    var asciiLength = $.asciiLength(value);

    return this.optional(element) ||
        (range[0] == null || asciiLength < range[0]) ||
        (range[1] == null || asciiLength > range[1]);
}, jQuery.format(""));


$.validator.addMethod(
    "customRemote",
    function (value, element, param) {
        var url = param.url;
        var method = param.method;
        var withNames = param.withNames;

        var data ="";

        //如果需要合并其他字段的数据
        if (typeof withNames !="undefined" && withNames!=null && withNames.length>0) {
            var selector = "";

            for (var i = 0; i < withNames.length; i++) {
                selector += "[name=" + withNames[i] + "]";

                if (i!=withNames.length-1) {
                    selector += ",";
                }
            }

            data=$(selector).serialize();
        }

        if (data !== "") {
            data = data + "&";
        } 

        data = data + $(element).attr("name") + "=" + value;

        var validator = this;

        $.ajax({
            url: url,
            method: method,
            data: data,
            cache: false,
            context: validator.currentForm,
            success: function(response) {
                if (response.IsSuccess) {
                    validator.resetInternals();
                    validator.toHide = validator.errorsFor(element);
                    validator.formSubmitted = validator.formSubmitted;
                    validator.successList.push(element);
                    validator.invalid[element.name] = false;
                    validator.showErrors();
                } else {
                    var errors = {};
                    var message = response.Message;
                    errors[element.name] = message;
                    validator.invalid[element.name] = true;
                    validator.showErrors(errors);
                }

                validator.stopRequest(element, response.IsSuccess);
            },
            error: function(jqXHR, textStatus, errorThrown) {

            }
        });

        return "正在检查....";
    },
    "远程校验错误"
);

var setupValidaor=function (collection) {
    if (window.requestRules) {
        if (!window.messageJson) {
            window.messageJson = {};
        }

        collection = $(collection);

        if (!collection.is("form:not(.fakeform)")) {
            collection = $(collection).find("form:not(.fakeform)");
        }

        $(collection).each(function () {
            $(this).validate(
                {
                    //debug: true,
                    ignore: '*:not([name])',
                    rules: requestRules,
                    messages: messageJson,
                    onkeyup:function(element, event) {

                        // Avoid revalidate the field when pressing one of the following keys
                        // Shift       => 16
                        // Ctrl        => 17
                        // Alt         => 18
                        // Caps lock   => 20
                        // End         => 35
                        // Home        => 36
                        // Left arrow  => 37
                        // Up arrow    => 38
                        // Right arrow => 39
                        // Down arrow  => 40
                        // Insert      => 45
                        // Num lock    => 144
                        // AltGr key   => 225
                        var excludedKeys = [
                            16, 17, 18, 20, 35, 36, 37,
                            38, 39, 40, 45, 144, 225
                        ];

                        if (event.which === 9 && this.elementValue(element) === "" || $.inArray(event.keyCode, excludedKeys) !== -1) {
                            return;
                        } else if (element.name in this.submitted || element.name in this.invalid) {
                            this.element(element);
                        }
                        else if (event.which === 8 || event.which === 9) {
                            this.element(element);
                        }
                    },
                    errorPlacement: function (error, element) {
                        //debugger;

                        //console.log("触发error");

                        var errorMsg = $(error).text();

                        if (errorMsg!=="") {
                            var fieldCtrl = $(element).closest(".webui-form_formfield,.webui_data_cell");

                            if (!fieldCtrl.is(".has-error")) {
                                fieldCtrl.addClass("has-error");
                            }
                            
                            fieldCtrl.find(".field-errormsg").text(errorMsg);
                        }
                        
                        //error.appendTo(element.parent("td").next("td"));
                    },
                    //success: function (error, element) {
                    //    // debugger;
                    //    console.log("触发success");
                    //    var fieldCtrl = $(element).closest(".webui-form_formfield");
                    //    fieldCtrl.removeClass("has-error");
                    //    fieldCtrl.find(".field-errormsg").text('');
                    //},
                    unhighlight: function (element, errorClass, validClass) {
                        
                        var fieldCtrl = $(element).closest(".webui-form_formfield,.webui_data_cell");

                        if (fieldCtrl.is(".has-error")) {
                            fieldCtrl.removeClass("has-error");
                            fieldCtrl.find(".field-errormsg").text('');
                        }


                        
                    }
                }
            ); 

            $(this).find("textarea").on("summernote.change",
                function () {
                    $(this).closest("form").validate().element($(this));
                });

            $(this).find("input[type=hidden]").change(function () {
                $(this).closest("form").validate().element($(this));
            });

        });


    }
}